#include "applyfrienditem.h"
#include <QMouseEvent>
#include <QPainter>
#include <QStyle>
#include <QStyleOption>
#include "authenfriend.h"
#include "ui_applyfrienditem.h"
#include "usermgr.h"
ApplyFriendItem::ApplyFriendItem(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ApplyFriendItem)
    , _applyInfo(nullptr)
    , _accepted(false)
{
    ui->setupUi(this);
    ui->apply_accept_btn->installEventFilter(this);
}

ApplyFriendItem::~ApplyFriendItem()
{
    delete ui;
}

void ApplyFriendItem::setInfo(std::shared_ptr<ApplyInfo> applyInfo)
{
    _applyInfo = applyInfo;
    // 加载头像
    QPixmap pix(_applyInfo->icon);
    pix = pix.scaled(ui->apply_avatar->size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
    ui->apply_avatar->setPixmap(pix);
    // 设置用户名
    ui->apply_name_lb->setText(_applyInfo->name);
    // 设置连天申请信息
    ui->apply_msg_lb->setText(_applyInfo->desc);
    // 确定消息是否已经处理
    if (applyInfo->status == 0) {
        // 已处理
        setAcceptBtnState(true);
    } else {
        // 未处理
        setAcceptBtnState(false);
    }
}

void ApplyFriendItem::setAcceptBtnState(bool accepted)
{
    _accepted = accepted;
    if (_accepted) {
        ui->apply_accept_btn->setProperty("state", "Accepted");
        ui->apply_accept_btn->setText("已添加");
        style()->unpolish(ui->apply_accept_btn);
        style()->polish(ui->apply_accept_btn);
        update();
    } else {
        ui->apply_accept_btn->setProperty("state", "Noaccepted");
        ui->apply_accept_btn->setText("添加");
        style()->unpolish(ui->apply_accept_btn);
        style()->polish(ui->apply_accept_btn);
        update();
    }
}

int ApplyFriendItem::getUid()
{
    return _applyInfo->uid;
}

QSize ApplyFriendItem::sizeHint() const
{
    return QSize(250, 80);
}

bool ApplyFriendItem::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == ui->apply_accept_btn) {
        if (event->type() == QEvent::MouseButtonPress) {
            auto me = static_cast<QMouseEvent *>(event);
            if (me->button() == Qt::LeftButton) {
                // 好友申请未被接收时，发送鼠标点击事件
                if (!_accepted) {
                    auto btn = qobject_cast<QPushButton *>(watched);
                    emit btn->clicked(true);
                }
                return true;
            }
        }
    }
    return QWidget::eventFilter(watched, event);
}

void ApplyFriendItem::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    QPainter p(this);
    opt.initFrom(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p);
    return QWidget::paintEvent(event);
}

void ApplyFriendItem::on_apply_accept_btn_clicked()
{
    int self_uid = UserMgr::GetInstance()->GetUid();
    if (self_uid == _applyInfo->uid) {
        return;
    }
    AuthenFriend *authFriend = new AuthenFriend(this);
    authFriend->setApplyInfo(_applyInfo);
    authFriend->show();
}
